package com.wfh.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.protocol.HTTP;

import com.wfh.R;
import com.wfh.adapter.PopupAdapter;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

public class Util {
	/*
	 * // commandrecevier 接收器 public static final String C_LOGIN = "c.login";//
	 * 登陆 public static final String C_LOGININIT = "c.logininit";// 登陆初始化 public
	 * static final String C_MESSAGE = "c.message";// 通知通告url
	 */
	// datarecevier 接收器
	public static final String D_INIT = "d.init";// 初始化详情
	public static final String D_HOME = "d.home";// 首页
	public static final String D_LOGIN = "d.login"; // 登陆
	public static final String D_ORDER = "d.order";
	public static final String D_PRODUCT = "d.product";
	public static final String D_SHOPS = "d.shops";
	public static final String D_PHONE = "d.phone";
	public static final String D_TICKETS = "d.tickets";
	public static final String D_MYTICKETS = "d.mytickets";
	public static final String D_QTICKETS = "d.qtickets";
	public static final String D_SETTING = "d.setting";
	public static final String D_REGIST = "d.regist";
	public static final String D_LOGININ = "d.loginin";
	public static final String D_FINDPASSWORD = "d.findpassword";
	public static final String D_SHARELIST = "d.sharelist";
	// 版本存储 app.properties
	public static final String V_INIT = "shopsversion";

	// 分享变量
	/*
	 * 新浪=sinatoken sinaexpires
	 * 
	 * qq空间=qqtoken qqexpires qqopenid
	 */

	// 缓存文件名
	public static String CACHEBANNER = "banner";

	// 分页大小
	public static int limit = 12;

	// 缓存文件夹
	public static String CACHE = getSdPath() + "/wfh/cache/";

	/**
	 * startActivity
	 * 
	 * @param context
	 * @param class1
	 */
	public static void startactivity(Context context, Class<?> class1) {
		Intent intent = new Intent();
		intent.setClass(context, class1);
		context.startActivity(intent);
	}

	/**
	 * startService
	 */

	public static void startservice(Context context, Class<?> class1) {
		Intent intent = new Intent(context, class1);
		context.startService(intent);
	}

	/**
	 * bindService
	 */
	public static void bindservice(Context context, Class<?> class1,
			ServiceConnection conn) {
		Intent intent = new Intent(context, class1);
		context.getApplicationContext().bindService(intent, conn,
				Context.BIND_AUTO_CREATE);
	}

	/**
	 * 注册接收广播
	 */

	public static void registreceiver(Context context,
			BroadcastReceiver recevier, IntentFilter actionfilter) {
		context.registerReceiver(recevier, actionfilter);
	}

	/**
	 * 发送广播
	 */
	public static void sendbroadcast(Context context, String action, Bundle bd) {
		Intent intent = new Intent();
		if (bd != null) {
			intent.putExtras(bd);
		}
		intent.setAction(action);
		context.sendBroadcast(intent);
	}

	/**
	 * toast显示
	 */

	public static void showToast(Context context, String message) {
		Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 获取json数据
	 * 
	 * @param suburl
	 *            url地址
	 * @param params
	 *            请求参数
	 */

	public static String getJson(String action, List<NameValuePair> params) {
		UrlEncodedFormEntity entity1 = null;
		try {
			entity1 = new UrlEncodedFormEntity(params, HTTP.UTF_8);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 请求服务器url
		String url = HttpUtil.BASE_URL + "&a=" + action;
		// Log.i("url", url);
		// 获得请求对象HttpPost
		HttpPost request = HttpUtil.getHttpPost(url);
		// 设置查询参数
		request.setEntity(entity1);
		// 获得响应结果
		String result = HttpUtil.queryStringForPost(request);
		// Log.i("result",result);
		if (result == null || result.equals("网络异常！")) {
			result = "false";
		}

		return result;

	}

	/**
	 * 获取json数据
	 * 
	 * @param suburl
	 *            url地址
	 * @param params
	 *            请求参数
	 */

	public static String getAJson(String module, String action,
			List<NameValuePair> params) {
		if (module == null)
			module = "Account";
		UrlEncodedFormEntity entity1 = null;
		try {
			entity1 = new UrlEncodedFormEntity(params, HTTP.UTF_8);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 请求服务器url
		String url = HttpUtil.MBASE_URL + module + "&a=" + action;
		Log.i("url", url);
		// 获得请求对象HttpPost
		HttpPost request = HttpUtil.getHttpPost(url);
		// 设置查询参数
		request.setEntity(entity1);
		// 获得响应结果
		String result = HttpUtil.queryStringForPost(request);
		// Log.i("result",result);
		if (result == null || result.equals("网络异常！")) {
			result = "false";
		}

		return result;

	}

	/**
	 * ------------------- 存储配置信息
	 * 
	 * @parame context 上下文
	 * @parame name 键名 --------------
	 */

	public static void saveShare(Context context, String name, String value) {
		Editor editor = context.getSharedPreferences("wfh",
				context.MODE_PRIVATE).edit();
		editor.putString(name, (String) value);
		editor.commit();
	}

	/**
	 * 获取存储信息
	 * 
	 * @parame context 上下文
	 * @parame name 键名
	 */
	public static String getShare(Context context, String name) {

		SharedPreferences share = context.getSharedPreferences("wfh",
				context.MODE_PRIVATE);
		return share.getString(name, null);

	}

	/**
	 * 获取资源文件的string
	 * 
	 * @param context
	 *            上下文
	 * @param id
	 *            string资源id
	 */
	public static String getRString(Context context, Integer id) {
		return context.getResources().getString(id);
	}

	/**
	 * 判断是否连接网络且是电信用户
	 */
	public static boolean isconnect(final Context context) {

		try {
			ConnectivityManager manager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = manager
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (info != null && info.isAvailable()) {
				TelephonyManager tm = (TelephonyManager) context
						.getSystemService(Context.TELEPHONY_SERVICE);
				String imsi = tm.getSimOperator();
				// if (imsi.startsWith("46003")) { return true; }
				return true;
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}

	/*
	 * 获取当前程序的版本号
	 */

	public static String getVersionName(Context context) {
		// 获取packagemanager的实例
		PackageManager packageManager = context.getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = null;
		try {
			packInfo = packageManager.getPackageInfo(context.getPackageName(),
					0);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return packInfo.versionName;
	}

	/**
	 * 解决scrollview嵌套listview显示问题
	 * 
	 * @param listView
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		// 获取ListView对应的Adapter
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		// listView.getDividerHeight()获取子项间分隔符占用的高度
		// params.height最后得到整个ListView完整显示需要的高度
		listView.setLayoutParams(params);
	}

	// 显示对话框
	public static Dialog alertDialog(Context context, View view, String title,
			String content) {
		Dialog alertDialog;
		if (view != null) {
			alertDialog = new AlertDialog.Builder(context).setView(view)
					.setTitle(title).create();
		} else {
			alertDialog = new AlertDialog.Builder(context).setTitle(title)
					.setMessage(replaceHtml(content)).create();
		}
		alertDialog.setCanceledOnTouchOutside(true);
		return alertDialog;
	}

	public static PopupWindow getPopupWindow(Context context, View parent,
			ArrayList<String> data) {
		PopupWindow popupWindow = null;
		View view;
		ListView lv_group = null;
		if (popupWindow == null) {
			LayoutInflater layoutInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = layoutInflater.inflate(R.layout.activity_popupgroup, null);
			lv_group = (ListView) view.findViewById(R.id.listView1);
			PopupAdapter groupAdapter = new PopupAdapter(context, data);
			lv_group.setAdapter(groupAdapter); // 创建一个PopuWidow对象
			popupWindow = new PopupWindow(view, 200, 300);
		}

		// 使其聚集 popupWindow.setFocusable(true); // 设置允许在外点击消失
		popupWindow.setOutsideTouchable(true);

		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(context.getResources().getDrawable(
				R.drawable.popup));
		return popupWindow;
	}

	// getdate日期为"Y-m-d"

	public static String strFormat(String str) {

		return str.substring(0, 10);
	}

	// 去除html

	public static String replaceHtml(String html) {
		String regEx = "<[^>]+>"; // 表示标签
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(html);
		String s = m.replaceAll("");
		return s;
	}

	// 获取Properties对象
	public static Properties getProperties(Context context) {
		Properties prop = new Properties();
		try {
			InputStream fis = context.getAssets().open("app.properties");
			prop.load(fis);
			fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return prop;
	}

	// 获取properties属性值
	public static String getProperty(Context context, String key) {
		Properties prop = Util.getProperties(context);
		return prop.getProperty(key);
	}

	// 得到Imagename
	public static String getImageFullName(String url) {
		return CACHE + getImageName(url);
	}

	// 得到Imagename
	public static String getImageName(String url) {
		String fullname = url.substring(url.lastIndexOf("/") + 1, url.length());

		return fullname.substring(0, fullname.lastIndexOf("."));
	}

	// http网络获取bitmap

	public static Bitmap getBitmap(String url, int insamplesize) {

		URL http;
		try {
			String filename = getImageName(url);
			String filePath = lookforFile(filename);
			BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
			bmpFactoryOptions.inSampleSize = insamplesize == 0 ? 1
					: insamplesize;

			// Log.i("文件名",filePath);
			if (filePath != null) {
				// Log.i("我没调用网络图片","yes");
				Bitmap tempbitmap=BitmapFactory.decodeFile(filePath, bmpFactoryOptions);
				Log.i("bitmap1", tempbitmap.toString());
				return tempbitmap;
			}
			http = new URL(HttpUtil.WEB_URL + url);
			// Log.i("地址",HttpUtil.WEB_URL+ url);
			Bitmap tempbitmap = BitmapFactory.decodeStream(http.openStream(),
					null, bmpFactoryOptions);
			bitmapToFile(tempbitmap, filename);
			Log.i("bitmap1", tempbitmap.toString());
			return tempbitmap;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} catch(OutOfMemoryError e){
			e.printStackTrace();
		}
		return null;
	}

	// 查找文件夹中是否有此文件
	public static String lookforFile(String fileName) {
		// 获取cache路径
		File f = new File(CACHE);
		if (!f.exists()) {// 创建缓存文件夹
			File file = new File(Util.CACHE);
			file.mkdirs();
		}
		if (f.exists() && f.isDirectory()) {
			File[] files = f.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].getName().equals(fileName))
					return files[i].getAbsolutePath();
			}
		}
		return null;
	}

	// 获取sd卡路径
	public static String getSdPath() {
		return Environment.getExternalStorageDirectory().getAbsolutePath();
	}

	// 把缓存压缩到缓存文件夹中
	public static void bitmapToFile(Bitmap bitmap, String filename) {
		File file = new File(CACHE + filename);
		Log.i("bitmap2", bitmap.toString());
		FileOutputStream fos;
		try {
			if (!file.exists())
				file.createNewFile();
			fos = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// 获取本机mac地址

	public static String getMacAdd(Context context) {
		WifiManager wifi = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = (wifi == null ? null : wifi.getConnectionInfo());
		return info == null ? null : info.getMacAddress();
	}

	/**
	 * 判断是否有可用的wifi网络 *
	 * 
	 * @return
	 */
	public static boolean isWIFIAvailable(Context context) {
		for (int i = 0; i < 5; i++) {
			ConnectivityManager cwjManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo wifiInfo = cwjManager.getActiveNetworkInfo();
			if (wifiInfo == null) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				continue;
			} else {
				if (wifiInfo.getType() == ConnectivityManager.TYPE_WIFI)
					return true;
			}

		}
		return false;
	}

	/**
	 * * 判断是否有可用的网络连接
	 * 
	 * @return
	 */
	public static boolean isNetWorkAvailable(Context context) {
		for (int i = 0; i < 5; i++) {
			ConnectivityManager cwjManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo netInfo = cwjManager.getActiveNetworkInfo();
			if (netInfo == null) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				continue;
			} else {
				if (netInfo.isAvailable()) {
					return true;
				} else
					continue;
			}
		}
		return false;
	}

	// 获取当前时间
	@SuppressLint("SimpleDateFormat")
	public static String getTime(String foramtstr) {
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(foramtstr);// 可以方便地修改日期格式
		return dateFormat.format(now);
	}

	// 比较时间大小
	@SuppressLint("SimpleDateFormat")
	public static int compare_date(String date1, String date2) {
		DateFormat df = new SimpleDateFormat("hh-mm-ss");
		try {
			java.util.Date d1 = df.parse(date1);
			java.util.Date d2 = df.parse(date2);
			if (d1.getTime() > d2.getTime()) {
				return 1;
			} else if (d1.getTime() < d2.getTime()) {
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return 0;
	}

	// 正则表达式

	public static boolean isexist(String reg, String str) {
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(str);
		if (matcher.find())
			return true;
		return false;
	}

	public static byte[] bmpToByteArray(final Bitmap bmp,
			final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.JPEG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}

		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
